<template>
  <view class="myPreferential">
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <view class="couponSetion" v-if="showGetCoupon == 0">
      <view class="coupon-contenter">
        <!-- 优惠券列表 -->
        <view class="coupon-items" v-if="couponLists.length > 0">
          <block v-for="(item, index) in couponLists" :key="index">
            <view class="couponItem">
              <h4>{{ item.couponRule.ruleName }}</h4>
              <h5>券码：{{ item.couponCode }}</h5>
              <block v-if="item.timesLimit > 0 && item.timesUsed >= item.timesLimit">
                <view class="stateIconUsed"><span>已使用</span></view>
              </block>
              <block v-else>
                <block v-if="item.outOfDate == true">
                  <view class="stateIconUsed"><span>已过期</span></view>
                </block>
                <block v-else>
                  <view class="stateIcon"><span>已领取</span></view>
                </block>
              </block>
              <view class="copRule">
                <span class="iconfont icon-jiantou32" @click="couponDescription" :data-index="index">使用规则</span>
                有效期至 {{ item['couponRule'].toDate }}
              </view>
              <view :class="index === currentIndexCoupon ? 'active' : 'couponRule'">{{ item['couponRule'].description }}</view>
            </view>
          </block>
        </view>
      </view>
      <view class="useCoupon" v-if="couponLists.length > 0"><view class="btn" @click="clickUseCoupon">使用优惠</view></view>
    </view>
    <!--暂无数据显示-->
    <view v-if="showGetCoupon == 1 || (showGetCoupon == 0 && couponLists.length <= 0)"><placeholder :is_empty.sync="is_empty" message="暂无优惠券"></placeholder></view>
  </view>
</template>
<script>
import { MERCHANT_INFO, CUSTOMER_INFO, SYSTEM_INFO } from '../../utils/constant';
import Placeholder from '../../components/common/placeholder';
import api from '@/api/api';
import tip from '@/utils/tip';
import NavBar from '../../components/common/navbar';
export default {
  config: {
    navigationBarTitleText: '我的优惠',
    enablePullDownRefresh: true
  },
  components: {
    navBar: NavBar,
    placeholder: Placeholder
  },
  data() {
    return {
      isShowCustomNavBar: true,
      navbarData: {
        showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
        title: '' ,//导航栏 中间的标题
        hideHome: true
      },
      is_empty: false,
      showGetCoupon: -1, // 0 是会员可以领优惠券 1 不是 不可领取
      jwt: '',
      currentPage: 0, //当前页面
      pageTotal: 0, //总页数
      pageSize: 20,
      preventRepeatReuqest: false, //防止重复加载
      couponLists: [], // 优惠券列表,
      couponListsArr: [],
      currentIndexCoupon: -1,
      nowPages:'',
    };
  },
  onShow(opts) {
    let that = this;
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    let jwt = customerInfo.jwt;
    that.jwt = jwt;
    that.getMemberDetail(jwt);
    let pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    this.nowPages = currPage.route;
    getApp().cl_tracker.track('mini_program_view', {
          path:  this.nowPages,
          pageName: '优惠券列表',
        })
  },
  //下拉刷新
  onPullDownRefresh() {
    let that = this;
    let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
    that.getMemberDetail(customerInfo.jwt);
    uni.stopPullDownRefresh();
  },
  methods: {
    /**
     * 判断是否是会员
     *
     * @param jwt
     * @return {Promise<void>}
     */
    getMemberDetail: async function(jwt) {
      let that = this;
      const memberDetailsResult = await api.getMemberDetails({
        header: {
          jwt: jwt
        }
      });
      if (memberDetailsResult.code == 1000) {
        const phoneNumberReg = /^1\d{10}$/;
        if(!phoneNumberReg.test(memberDetailsResult.data.mobile)){
          // 非大陆手机号按照非会员对待,重新入会
          uni.removeStorageSync('memberDetails');
          that.is_empty = true;
          return;
        }
        let memberDetails = memberDetailsResult.data;
        if (memberDetails.isActive == 'Inactive') {
          that.showGetCoupon = 1;
          that.is_empty = true;
        } else {
          that.showGetCoupon = 0;
          that.is_empty = false;
          that.getMemberCouponsList(jwt);
        }
      } else {
        // that.showGetCoupon = 1;
        that.is_empty = true;
      }
    },
    /**
     * 获取用户优惠券列表
     * 根据couponId去重
     */
    getMemberCouponsList: async function(jwt) {
      let that = this;
      const memberCouponList = await api.getMemberCoupons({
        method: 'GET',
        header: {
          jwt: jwt
        },
        query: {
          page: that.currentPage,
          size: that.pageSize
        }
      });
      if (memberCouponList.code === 1000 && memberCouponList.data.content.length > 0) {
        that.couponListsArr = [...that.couponListsArr, ...memberCouponList.data.content];
        that.pageTotal = memberCouponList.data.totalPages;

        // 去重 根据couponId去重
        let obj = {};
        that.couponLists = that.couponListsArr.reduce((cur, next) => {
          obj[next.couponId] ? '' : (obj[next.couponId] = true && cur.push(next));
          return cur;
        }, []); //设置cur默认类型为数组，并且初始值为空的数组

        let c_item = [];
        let couponFailureTime = '';
        for (let j in that.couponLists) {
          c_item = that.couponLists[j];

          if (c_item.expirationDate != null && (c_item.expirationDate != undefined) & (c_item.expirationDate != '')) {
            couponFailureTime = that.UTCformat(c_item.expirationDate);
          } else {
            couponFailureTime = that.UTCformat(c_item['couponRule'].toDate);
          }

          let timearr = couponFailureTime.split(' '); //只取年月日
          c_item['couponRule'].toDate = timearr[0];

          let toDateTimestamp = Date.parse(couponFailureTime.replace(/-/g, '/'));
          var timestamp = new Date().getTime();
          if (timestamp > toDateTimestamp) {
            c_item['outOfDate'] = true;
          }

          if (c_item['couponRule'].description == null || c_item['couponRule'].description == '' || c_item['couponRule'].description == undefined) {
            c_item['couponRule'].description = '';
          }
        }

        // that.showGetCoupon = 0;
        // that.is_empty = false;
      } else {
        // that.showGetCoupon = 1;
        that.is_empty = true;
      }
    },
    //加载更多
    onReachBottom() {
      let that = this;
      //判断总页数是否大于翻页数
      if (that.pageTotal > that.currentPage) {
        //防止重复加载
        if (that.preventRepeatReuqest) {
          return true;
        }
        that.preventRepeatReuqest = true;
        that.currentPage++;
        that.getMemberCouponsList(that.jwt);
        that.preventRepeatReuqest = false;
      } else {
        that.showLoading = false;
      }
    },
    // UTC转为北京时间
    UTCformat(utc) {
      var date = new Date(utc),
        y = date.getFullYear(),
        month = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + parseInt(date.getMonth() + 1),
        day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate(),
        h = date.getHours() > 9 ? date.getHours() : '0' + date.getHours(),
        m = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes(),
        s = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds();
      var res = y + '-' + month + '-' + day + ' ' + h + ':' + m;
      return res;
    },
    // 使用优惠券
    clickUseCoupon() {
      uni.reLaunch({
        url: '/pages/home/home'
      });
    },
    // 点击显示优惠券规则
    couponDescription(e) {
      let index = e.currentTarget.dataset.index;
      if (index == this.currentIndexCoupon) {
        this.currentIndexCoupon = -1;
      } else {
        this.currentIndexCoupon = e.currentTarget.dataset.index;
      }
    }
  }
};
</script>
<style lang="less">
.coupon-contenter {
  padding-bottom: 160rpx;
}

.couponItem {
  background-color: #f5f5f5;
  padding: 40rpx;
  margin: 20rpx 30rpx;
  position: relative;
}

.couponItem h4 {
  font-size: 36rpx;
  display: block;
  margin-bottom: 10rpx;
}

.couponItem h5 {
  font-size: 32rpx;
  display: block;
  margin-bottom: 20rpx;
}

.couponItem .coupon-get {
  width: 160rpx;
  color: #fff;
  background: #444;
  text-align: center;
  height: 50rpx;
  line-height: 56rpx;
  font-size: 30rpx;
  display: block;
  margin-bottom: 20rpx;
}

.couponItem .copRule {
  border-top: 1px solid #d2d2d2;
  padding-top: 24rpx;
  text-align: right;
  overflow: hidden;
}

.couponItem .copRule span {
  float: left;
}

.couponItem .couponRule {
  padding-top: 24rpx;
  overflow: hidden;
  display: none;
}

.couponItem .active {
  padding-top: 24rpx;
  overflow: hidden;
  display: block;
}

.couponItem .stateIcon {
  position: absolute;
  right: 36rpx;
  top: 30rpx;
  border: 2px solid #ba3533;
  border-radius: 100rpx;
  width: 110rpx;
  height: 110rpx;
}

.couponItem .stateIcon span {
  color: #ba3533;
  transform: rotate(-30deg);
  width: 110rpx;
  height: 110rpx;
  display: block;
  margin: 25rpx 0 0 30rpx;
}

.couponItem .stateIconUsed {
  position: absolute;
  right: 36rpx;
  top: 30rpx;
  border: 2px solid #666;
  border-radius: 100rpx;
  width: 110rpx;
  height: 110rpx;
}

.couponItem .stateIconUsed span {
  transform: rotate(-30deg);
  width: 110rpx;
  height: 110rpx;
  display: block;
  margin: 25rpx 0 0 30rpx;
}

.couponItem .copRule .iconfont {
  font-size: 26rpx;
}

.couponItem .copRule .icon-jiantou32:before,
.couponItem .copRule .icon-jiantou31:before {
  content: '';
}

.couponItem .copRule .icon-jiantou32:after {
  content: '\e72e';
}

.couponItem .copRule .icon-jiantou31:after {
  content: '\e72d';
}

.useCoupon {
  background-color: #fff;
  width: 100%;
  height: 60px;
  position: fixed;
  z-index: 1000;
  bottom: 0;

  .btn {
    position: fixed;
    bottom: 30rpx;
    width: 90%;
    height: 80rpx;
    line-height: 80rpx;
    left: 5%;
  }
}
</style>
